/**
 *	流程模块主Flow列表页
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-22
 */

package com.framework.Flow;




import com.framerock.baselib.CLog;
import com.framerock.baselib.RockList;
import com.framerock.db.DB;
import com.framerock.baselib.Jiami;
import com.framerock.baselib.Json;
import com.framerock.baselib.Patter;
import com.framerock.baselib.Rock;
import com.framerock.baselib.RockMsg;
import com.framework.ACore.Model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class FlowList extends FlowBase {

    public FlowList(Flow flows) {
        super(flows);
    }

    //所有文件id
    public String allFileids = "";

    /**
     * 列表页数据
     * */
    public ArrayList<Map<String, String>> getFlowData()
    {
        if(mFlow.isError())return null;
        Map<String, String> before  = mFlow.mFlowListener.onDatabefore();
        String where = "1=1",fields = "*",order = "",groupby = "",asqom="",table = DB.chuliPerfix(mFlow.table),str;

        str = mFlow.cidWhere(2);
        if(!Rock.isEmpt(str))where = ""+str+"";


        if(before != null) {
            str = Rock.getMapString(before, "where");
            if(!Rock.isEmpt(str))where += " AND "+str+"";

            str = Rock.getMapString(before, "table");
            if(!Rock.isEmpt(str))table = str;

            str = Rock.getMapString(before, "fields");
            if(!Rock.isEmpt(str))fields = str;

            order   = Rock.getMapString(before, "order");
            groupby = Rock.getMapString(before, "groupby");
            asqom   = Rock.getMapString(before, "asqom");
        }

        //读取模块条件里面的
        if(!Rock.isEmpt(mFlow.atype)) {
            str = mFlow.getFlowwhere(mFlow.atype, asqom);
            if(!Rock.isEmpt(str))where += " AND "+str+"";
        }

        String sqlwhere = mRequest.get("sqlwhere");
        if(!Rock.isEmpt(sqlwhere)){
            sqlwhere = Jiami.base64decode(sqlwhere);
            if(!Rock.contain(sqlwhere, "(") && !Rock.contain(sqlwhere, ")")){
                where += " AND "+sqlwhere+"";
            }
        }

        str     = Rock.getMapString(mFlow.moders, "where");
        if(!Rock.isEmpt(str))where+=" AND "+str+"";

        if(Rock.isEmpt(order))order = mFlow.getOrderstr();
        if(Rock.isEmpt(order))order = ""+asqom+"`id` DESC";

        Map<String, String> da;
        int i,len;
        String key = mRequest.get("key");
        String type,fid,dbtype;
        ArrayList<Map<String, String>> farr = null;

        //关键词搜索
        if(!Rock.isEmpt(key)) {
            key  = Jiami.base64decode(key);
            farr = mFlow.getFieldsArr(2);
            len  = farr.size();
            String keywhere = "";
            for (i = 0; i < len; i++) {
                da     = farr.get(i);
                type   = da.get("fieldstype");
                dbtype = this.dbTypes(da.get("dbtype"));
                fid    = da.get("fields");
                if(!da.get("isss").equals("1"))continue;
                if(dbtype.equals("int")){
                    if(Patter.isnumber(key))keywhere += " OR "+asqom+"`"+fid+"` = "+key+"";
                }else if(type.equals("text") || type.equals("textarea") || type.indexOf("change")==0 || type.indexOf("selectdata")==0){
                    keywhere += " OR "+asqom+"`"+fid+"` LIKE '%"+key+"%'";
                }else if(type.equals("select") || type.equals("rockcombo")){
                    keywhere += " OR "+asqom+"`"+fid+"` = '"+key+"'";
                }
            }
            if(!Rock.isEmpt(keywhere)){
                where += " AND ("+keywhere.substring(4)+")";
            }
        }

        ArrayList<Map<String, String>> data = mFlow.mDBLimit.getData(table, where, fields, order, groupby, asqom, null);
        //CLog.debug(DB.NOWSQL);
        if(this.nDb.isError())mFlow.setError(this.nDb.error());

        if(data == null)return data;

        return this.replaceRowsList(data);
    }

    /**
     * 列表处理替换
     * */
    public ArrayList<Map<String, String>> replaceRowsList(ArrayList<Map<String, String>> data)
    {
        ArrayList<Map<String, String>> store,rows = new ArrayList<Map<String, String>>(),farrrep = new ArrayList<Map<String, String>>();

        Map<String, String> da,da1,da2;
        int i,len,j,jlen,k,klen,zt;
        String type,fid,val,nval,key;
        ArrayList<Map<String, String>> farr = null;

        //字段数据源判断
        if(farr==null)farr    = mFlow.getFieldsArr(2);
        len     = farr.size();
        String varr[] = new String[]{"checkboxall","select","rockcombo","radio"},uploadfiles = "";

        for(i=0; i<len;i++) {
            da      = farr.get(i);
            type    = da.get("fieldstype");
            if(Rock.inArray(varr, type) && da.get("islb").equals("1")){
                farrrep.add(da);//需要从数据源读取
            }
            if(type.equals("uploadfile"))uploadfiles+=","+da.get("fields")+"";
        }
        if(!Rock.isEmpt(uploadfiles))uploadfiles = uploadfiles.substring(1);

        jlen    = farrrep.size();
        Map<String, Map<String, String>> storeAll = new HashMap<String, Map<String, String>>();
        if(jlen>0){
            mFlow.mFlowBase.Store().getallStore(0); //加载数据源
            for(j=0;j<jlen;j++){
                fid     = farrrep.get(j).get("fields");
                store   = mFlow.mFlowBase.Store().getallStoreList(fid);
                if(store != null) {
                    klen = store.size();
                    da2  = Rock.getMap();
                    for(k=0;k<klen;k++){
                        da1 = store.get(k);
                        val = da1.get("value");
                        da2.put("val_"+val, da1.get("name"));
                        key = Rock.getMapString(da1, "color");
                        if(!Rock.isEmpt(key))da2.put("col_"+val, key);
                    }
                    storeAll.put(fid, da2);
                }
            }
        }
        len     = data.size();
        String fileids = "",arr[],allids = "";
        for(i=0; i<len;i++) {
            da  = data.get(i);
            if(mFlow.isflow > 0)allids+=","+da.get("id")+"";

            //显示灰色的
            zt  = Integer.parseInt(Rock.getMapString(da, "status", "-1"));
            if(mFlow.isflow == 0 && !mFlow.modenum.equals("flowbill")){
                if(zt==0)da.put("isrowhui", "1");
            }
            if(zt==5)da.put("isrowhui", "1");//5固定作废

            da  = mFlow.mFlowListener.onReplacers(da, 2); //回调替换
            if(jlen>0)for(j=0;j<jlen;j++){
                fid = farrrep.get(j).get("fields");
                val = da.get(fid);
                if(Rock.isEmpt(val))continue;
                da1 = storeAll.get(fid);
                if(da1 != null) {
                    nval= replaceVal(val, da1, 0);
                    if(nval != null) {
                        da.put(fid+"_textcn", nval);
                        nval = replaceVal(val, da1, 1);
                        if(nval != null)da.put(fid+"_color", nval); //字体颜色
                    }
                }
            }
            if(!Rock.isEmpt(uploadfiles)){
                arr = uploadfiles.split(",");
                for(j=0;j<arr.length;j++){
                    fid = arr[j];
                    val = da.get(fid);
                    if(!Rock.isEmpt(val)){
                        if(!Rock.isEmpt(fileids))fileids+=",";
                        fileids += val;
                    }
                }
            }
            rows.add(da);
        }

        //读取单据里面的单号
        if(!Rock.isEmpt(allids)){
            allids = allids.substring(1);
            RockList rocklist = mFlow.mFlowBase.Bill().getBilllist(allids);
            String allida[]   = allids.split(",");
            for(i=0;i<allida.length;i++){
                da = rocklist.getKeyMap(allida[i]);
                if(da != null){
                    rows.get(i).put("nowcheckname", da.get("nowcheckname"));
                    rows.get(i).put("sericnum", da.get("sericnum"));
                    String ztna = rows.get(i).get("status_textcn");
                    if(Rock.contain(ztna, "?"))rows.get(i).put("status_textcn", ztna.replace("?", da.get("nowcheckname")));
                }
            }
        }

        this.allFileids = fileids;
        rows    = mFlow.mFlowListener.onDataafterList(rows);
        return rows;
    }

    //替换
    private String replaceVal(String key, Map<String, String> da, int lx)
    {
        if(da == null)return null;
        String nstr = "",kv,nv;
        if(lx==0){
            String arr[] = key.split(",");
            for(int i=0;i<arr.length;i++){
                kv = arr[i];
                nv = da.get("val_"+kv+"");
                if(nv==null)nv = kv;
                if(nstr.length()>0)nstr+=",";
                nstr+=nv;
            }
            return nstr;
        }
        if(lx==1){
            nstr = da.get("col_"+key+"");
        }
        return nstr;
    }

    //字段类型
    private String dbTypes(String dbtype)
    {
        String str = "text";
        if(Rock.contain(dbtype, "int(") || Rock.contain(dbtype, "decimal"))str = "int";
        if(dbtype.equals("date") || dbtype.equals("datetime"))str = dbtype;
        return str;
    }

    public String getAllFileids()
    {
        return this.allFileids;
    }


    /**
     * 获取所有子表数据
     * */
    public String getSubdataAll()
    {
        Json json = new Json();
        ArrayList<Map<String, String>> farr = mFlow.getFieldsArr(2);
        int i,len;
        Map<String, String> da;
        String type;
        len = farr.size();
        for(i=0;i<len;i++){
            da  = farr.get(i);
            type= da.get("fieldstype");
            if(type.equals("subdata")){
                json.putVal(da.get("fields"), this.getSubdata(da, mFlow.mid, 1));
            }
        }
        return json.getJson();
    }

    /**
     * 获取子表信息
     * */
    public String getSubdata(Map<String, String> da, String mids, int slx)
    {
        Json json = new Json();
        String str,num,fid,dstr="";
        Map<String, String> rs = mFlow.subdataInfo(da.get("data"));
        num = rs.get("num");
        fid = rs.get("fid");
        Flow flow = Flow.get(this.nDb, num, mRequest);
        json.putVal("fieldsarr", flow.getFieldsArr(2));
        ArrayList<Map<String, String>> data;
        data = flow.mModel.getAll("`"+fid+"` IN("+mids+")", "*", "`sort` ASC,`id` ASC");
        data = flow.replaceRowsList(data);
        str  = Rock.getMapString(flow.moders, "summary");
        int  len,i;
        if(!Rock.isEmpt(str) && data!=null){
            len = data.size();
            for(i=0;i<len;i++) {
                if (i > 0) dstr += ";";
                dstr+=""+(i+1)+"."+Rock.replaceString(str, data.get(i))+"";
            }
        }
        String fields= da.get("fields");
        if(slx==1 && da.get("islu").equals("1") && !Rock.isEmpt(dstr)) {
            String odstr = mFlow.getFieldsval(fields);
            if(!odstr.equals(dstr))mFlow.mModel.update("`"+fields+"`='"+dstr+"'", mids);
        }
        json.putVal("data", data);
        json.putVal("filedata", flow.getFiledata(2));
        json.putVal("name", da.get("name"));
        json.putVal("fieldskey", fid);
        json.putVal("fieldssub", fields);
        json.putVal("num", num);
        json.putVal("datastr", dstr);
        return json.getJson();
    }

    /**
     * 获取子表字段信息列表
     * */
    public String getSubdata(String zdid)
    {
        Map<String, String> rs = Model.get(this.nDb, "flowelement").getOne("`id`="+zdid+" and `modeid`="+mFlow.modeid+"");
        if(rs==null)return "";
        int mid      = Integer.parseInt(mRequest.get("mid", "0"));
        String mids  = mRequest.get("mids", "-1");
        if(mid>0)mids+=","+mid+"";
        return getSubdata(rs, mids, 0);
    }

    /**
     * 首页显示数据
     * */
    public String homeData(String pnum)
    {
        Json json = new Json();
        json.putVal("name", mFlow.unitrs.get("name"));
        json.putVal("funitid", mFlow.unitrs.get("id"));
        json.putVal("color", mFlow.unitrs.get("color"));
        json.putVal("icons", mFlow.unitrs.get("icons"));
        json.putVal("num", mFlow.modenum);
        json.putVal("pnum", mFlow.unitrs.get("url"));
        Map<String, String> da = mFlow.mFlowListener.onhomeData(pnum);
        if(da!=null){
            for(Map.Entry<String,String> entry:da.entrySet()){
                json.putVal(entry.getKey(), entry.getValue());
            }
        }else{
            return "";
        }
        return json.getJson();
    }

    /**
     * 双击单元格保存
     * */
    public RockMsg SaveCelledit()
    {
        RockMsg rockmsg = RockMsg.obj();
        String id       = mRequest.post("id");
        String fields   = mRequest.post("fieldname");
        String value    = mRequest.post("value");
        if(Rock.isEmpt(id) || Rock.isEmpt(fields) || !Patter.isnumber(id))return rockmsg.error("params error");
        RockMsg before  = mFlow.mFlowListener.onCellEditBefore(id,fields, value);
        if(before!=null && before.isError())return before;
        mFlow.initData(id);
        Boolean bo = mFlow.mModel.update("`"+fields+"`='"+value+"'", id);
        if(!bo)return rockmsg.error(this.nDb.error());
        mFlow.mFlowListener.onCellEditAfter(id,fields, value);
        return rockmsg.success();
    }

    /**
     * 根据模块条件获取列表数据
     * @param num 条件编号
     * @param fields 字段
     * @param limit 记录数
     * @param isreplace 是否列表页数据替换
     * */
    public ArrayList<Map<String, String>> getListData(String num, String fields, int limit, boolean isreplace)
    {
        String where = "`cid`=" + mFlow.COMPANYID + " AND " + mFlow.getFlowwhere(num) + "";
        ArrayList<Map<String, String>> data = mFlow.mModel.getAll(where, fields, mFlow.getOrderstr(), limit);
        if(!isreplace)return data;//不替换
        return this.replaceRowsList(data);
    }
}
